package com.chenjf.controller;


import com.chenjf.config.LoadBalanced;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("users")
@RestController
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    @Autowired
    private LoadBalanced loadBalanced;

    @GetMapping

    public String pingProductList() {

        /*RestTemplate restTemplate = new RestTemplate();
        List<ServiceInstance> products = discoveryClient.getInstances("PRODUCTS");
        for (ServiceInstance product : products) {
            System.out.println(product.getHost());
            System.out.println(product.getPort());
            System.out.println(product.getUri());

        }
        Random random = new Random();
        int i = random.nextInt(2);
        ServiceInstance serviceInstance = products.get(i);
        String forObject = restTemplate.getForObject(serviceInstance.getUri() + "/products", String.class);
        System.out.println("forObject = " + forObject);*/

        //3.
        String forObject = loadBalanced.restTemplate().getForObject("http://PRODUCTS/products", String.class);
        System.out.println("forObject = " + forObject);

        //2.
        /*ServiceInstance products = loadBalancerClient.choose("PRODUCTS");
        URI uri = products.getUri();*/

        return "users ok";
    }
}
